package service

import (
	"errors"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/zhang201702/zhang/zlog"
)

type PptPageService struct {
	BaseService
	PptTextService Service
}

func init() {
	registerService("ppt_page", func(name string) Service {
		return &PptPageService{
			BaseService:    newBaseService(name),
			PptTextService: NewService("ppt_text"),
		}
	})
}

func (service *PptPageService) Fetch(id string) (result g.Map, err error) {
	list, err := service.PptTextService.List(g.Map{"pageId": id})
	if err != nil {
		return nil, err
	}
	for i := range list {
		list[i]["options"] = service.toMap(list[i]["options"])
		list[i]["texts"] = service.toList(list[i]["texts"])
	}
	result = g.Map{"items": list}
	return result, nil
}
func (service *PptPageService) Save(data g.Map) (result interface{}, err error) {
	id := gconv.String(data["id"])
	if id == "" {
		return nil, errors.New("非法操作，id 不能为空!")
	}
	service.PptTextService.DeleteAll(g.Map{"pageId": id})

	items := gconv.Maps(data["items"])
	for i := range items {
		item := items[i]
		item["pptId"] = data["pptId"]
		item["pageId"] = data["id"]
		item["options"] = service.toMapString(item["options"])
		item["texts"] = service.toListString(item["texts"])

		_, er2 := service.PptTextService.Insert(item)
		if er2 != nil {
			zlog.Error(er2, "添加ppt明细异常(2)", item)
		}
	}
	return service.Fetch(id)
}

func (service *PptPageService) Delete(id string) (result interface{}, err error) {
	return service.PptTextService.DeleteAll(g.Map{"pageId": id})
}
